
const { sendRes, socketLinks, socketMap } = require('./data')
const { guid } = require('./utils')


module.exports = function (io) {

    io.on('connection', (socket) => {

        socketMap.addSocket(socket)
        socketLinks.addSocket(socket.id)

        socket.emit('open')

        console.log('@链接' + socket.id);

        socket.emit('socketInfo', socketLinks[socket.id])
    
        socket.on('send', function (data) {
            try{
                sendRes[data.code].send(data.data)
                delete sendRes[data.code]
            }catch(e){
                console.log(e);
            }
        });
    
        socket.on('delRouter', function (data) {
            console.log('delRouter', data);
            socketLinks.delRouter(socket.id, data.path)
            socket.emit('delRouter', {
                data : data.path,
                success : true
            })
        });

        socket.on('socketInfo', function (data) {
            socket.emit('socketInfo', socketLinks[socket.id])
        });

        socket.on('addRouter', (data) => {


            if(data.path){
                let msg = socketLinks.addRouter(socket.id, data.path, data)
                socket.emit('addRouter', {
                    msg,
                    success : !msg,
                    data
                })
                socket.emit('socketInfo', socketLinks[socket.id])
                return
            }

            let is = true
            while(is){
                data.path = guid().slice(0, 6)
                is = socketLinks.addRouter(socket.id, data.path, data)
            }
            socket.emit('addRouter', {
                success : true,
                data
            })

            socket.emit('socketInfo', socketLinks[socket.id])
        })
    
        socket.on('disconnect',() => {
            console.log("断开连接");
            socketLinks.delSocket(socket.id)
            socketMap.delSocket(socket.id)
        })
    });
    
}


